import request from "../../../plugins/request"
import store from "../../../utils/store"
import { checkPhone, controlShowPage, valIsNull } from "../../../utils/utils"
import { sc } from "../../../../towxml/parse/parse2/entities/maps/entities"

const pageOptions = {
	// 页面数据
	data: {
		inputForm: {
			xm: "", //姓名
			sfzh: "", //身份证号
			schoolId: "", //学校id
			sjh: "", //手机号
			yzm: "", //验证码
			openid: "",
		},
		formDataBind: {
			schoolName: "", //学校名称
		},
		schoolList: [], //学校列表
		disableSchoolPicker: false, //是否禁用学校选择器
		showPage: true, // 是否显示页面，用于微信审核

		needPhone: false, //是否需要输入手机号

		//检查输入的手机号码是否合法
		phoneValid(phoneNumber) {
			if (!phoneNumber) {
				wx.showToast({
					title: "请输入手机号码",
					icon: "none",
					duration: 3000,
				})
				console.log("手机号码验证不通过")
				return false
			}
			if (!checkPhone(phoneNumber)) {
				wx.showToast({
					title: "手机号码格式不正确",
					icon: "none",
					duration: 3000,
				})
				console.log("手机号码验证不通过")
				return false
			}
			console.log("手机号码验证通过")
			return true
		},
	},
	// 页面载入时
	onLoad(e) {
		let schoolId
		//扫描小程序二维码进入
		if (e.scene) {
			const scene = decodeURIComponent(e.scene)
			const sceneArr = scene.split("+")
			if (
				sceneArr &&
				sceneArr.length &&
				sceneArr.length > 0 &&
				sceneArr[0] === "IV"
			) {
				// 获取扫码带上的学校id
				schoolId = sceneArr[1]
			}
			//检查缓存里是否有学校id
		} else if (store.schoolId.get()) {
			schoolId = store.schoolId.get()
		}
		//禁用学校选择器
		schoolId && this.setData({ disableSchoolPicker: true })
		//获取学校列表
		this.getSchoolList(schoolId)
		// 获取微信code
		wx.login({
			success: (res) => {
				this.setData({
					inputForm: {
						...this.data.inputForm,
						openid: res.code,
					},
				})
			},
			fail: (err) => {
				console.log(err, "err")
				wx.showModal({
					title: "提示",
					content: "网络异常，请尝试重新打开小程序",
					showCancel: false,
				})
			},
		})
		//检查是否有token
		if (!valIsNull(store.token.get())) {
			//检查token是否过期
			if (
				store.tokenExpireAt.get() &&
				new Date().getTime() < store.tokenExpireAt.get()
			) {
				//没有过期跳转到首页
				wx.redirectTo({
					url: "/informationVerification/pages/index/index",
				})
				return
			} else {
				//清除过期的token
				store.token.set("")
			}
		}
	},
	// 页面显示时
	onShow() {
		this.setData({
			showPage: controlShowPage(),
		})
	},
	//获取学校列表
	getSchoolList(schoolId) {
		wx.showLoading({
			title: "加载中",
		})
		request({
			url: "api/wx/get-school-list",
			method: "get",
		})
			.then((data) => {
				this.setData({
					schoolList: data,
				})
				//根据学校id回显学校名称
				if (schoolId) {
					for (let i = 0; i < data.length; i++) {
						if (data[i].id === schoolId) {
							this.bindSchoolPickerChange({
								detail: {
									value: i,
								},
							})
							break
						}
					}
				}
			})
			.catch((err) => {
				console.log(err, "err")
				wx.showToast({
					title: err,
					icon: "none",
					duration: 3000,
				})
			})
			.finally(() => {
				wx.hideLoading()
			})
	},
	//选择学校
	bindSchoolPickerChange(e) {
		const value = this.data.schoolList[parseInt(e.detail.value)]
		const inputForm = this.data.inputForm
		const formDataBind = this.data.formDataBind
		this.setData({
			inputForm: {
				...inputForm,
				schoolId: value.id,
			},
			formDataBind: {
				...formDataBind,
				schoolName: value.schoolName,
			},
			//判断该学校是否有开启允许手机号码验证
			needPhone: value.mobileState === 1,
		})
		// 学校是否开启显示联系客服入口
		const showContractKefuBtn = value.contactState === 1
		store.showContractKefuBtn.set(showContractKefuBtn)
		wx.nextTick(() => {
			this.selectComponent("#contractKefuBanner").setData({
				showContractKefuBtn,
			})
		})
		//判断该学校是否有开启新生通知
		const showNewComerNoticeFloat = value.noticeState === 1
		store.showNewComerNoticeFloat.set(showNewComerNoticeFloat)
		wx.nextTick(() => {
			this.selectComponent("#forNewComersFloat").setData({
				show: showNewComerNoticeFloat,
			})
		})

		store.schoolId.set(value.id) // 缓存学校id
		this.selectComponent("#agreement").getAgreementDetail(value.id)
	},
	//提交
	async submit() {
		//检查用户输入
		const formItemInstanceList = this.selectAllComponents(".form-item")
		for (let wxComponent of formItemInstanceList) {
			if (!wxComponent.handleVerify()) {
				return
			}
		}
		//检查用户是否有同意协议
		const agreementInstance = this.selectComponent("#agreement")
		if (!agreementInstance.data.agreement) {
			//弹出弹框让用户同意协议
			agreementInstance.handleOpenAgreementDetail()
			return
		}
		const inputForm = JSON.parse(JSON.stringify(this.data.inputForm))
		//去除输入框里头部和尾部的空格
		inputForm.xm = inputForm.xm.trim()
		inputForm.sfzh = inputForm.sfzh.trim()
		//登录
		function login() {
			return new Promise((resolve, reject) => {
				request({
					url: "api/wx/login",
					method: "post",
					data: inputForm,
				})
					.then((data) => {
						resolve(data)
					})
					.catch((err) => {
						reject(err)
					})
			})
		}
		//获取用户信息
		function getUserInfo(token) {
			return new Promise((resolve, reject) => {
				request({
					url: "api/wx/get-user-info",
					method: "post",
					data: {
						token: token,
					},
				})
					.then((result) => {
						resolve(result)
					})
					.catch((err) => {
						reject(err)
					})
			})
		}
		try {
			wx.showLoading({ title: "登录中" })
			const loginRes = await login.call(this)
			wx.hideLoading()
			store.token.set(loginRes.token)
			//记录token的过期时间
			const tokenExpireAt = new Date().getTime() + loginRes.expire_time
			store.tokenExpireAt.set(tokenExpireAt)
			const userInfoRes = await getUserInfo(loginRes.token)
			store.userInfo.set(userInfoRes)
			wx.showToast({
				title: "登录成功",
				icon: "success",
				duration: 2000,
			})
			//跳转到首页
			wx.redirectTo({
				url: "/informationVerification/pages/index/index",
			})
		} catch (error) {
			wx.hideLoading()
			console.log(error, "error")
			wx.showToast({
				title: error,
				icon: "none",
				duration: 3000,
			})
		}
	},
	//绑定input输入
	inputChange(e) {
		const inputForm = this.data.inputForm
		this.setData({
			inputForm: {
				...inputForm,
				[e.currentTarget.dataset.prop]: e.detail.value,
			},
		})
	},
}

Page(pageOptions)
